package com.dhcc.sdc.base.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.dhcc.cdc.sys.entity.DictionaryEntity;
import com.dhcc.cdc.sys.service.IDictionaryService;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.core.framework.result.node.ZTreeNode;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.sdc.base.dao.ContraindicationItemMapper;
import com.dhcc.sdc.base.dao.ContraindicationMapper;
import com.dhcc.sdc.base.dao.ContraindicationQcentityMapper;
import com.dhcc.sdc.base.entity.SdcCdssContraindicationMatchEntity;
import com.dhcc.sdc.base.entity.ContraindicationEntity;
import com.dhcc.sdc.base.entity.ContraindicationItemEntity;
import com.dhcc.sdc.base.service.IContraindicationQcentityService;
import com.dhcc.sdc.base.service.IContraindicationService;
import com.dhcc.sdc.busi.dao.SdcBusiContraindicationDtlMapper;
import com.dhcc.sdc.busi.dao.SdcBusiContraindicationMapper;
import com.dhcc.sdc.busi.entity.SdcBusiContraindicationEntity;
import com.dhcc.sdc.cdss.dao.CdssApiMapper;
import com.dhcc.sdc.cdss.dao.SdcCdssItemMapper;
import com.dhcc.sdc.cdss.dto.SdsQcentityEntityDto;
import com.dhcc.sdc.cdss.service.ISdcCdssContraindicationMatchService;
import com.dhcc.sds.base.dao.SdsQcentityMapper;
import com.dhcc.sds.base.entity.SdsQcentityEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 病种相关禁忌症表数据服务层接口
 *
 * @ClassName:
 * @Description: TODO
 * @author zhangjin
 * @date 2022-8-31 09:49:29
 */
@Service("contraindicationService")
public class ContraindicationServiceImpl extends BaseServiceImpl<ContraindicationMapper, ContraindicationEntity> implements IContraindicationService {

	@Resource
	private SdcBusiContraindicationMapper sdcBusiContraindicationMapper;
	@Resource
	private SdcBusiContraindicationDtlMapper sdcBusiContraindicationDtlMapper;
	@Resource
	private IContraindicationQcentityService conQcentityService;
	@Resource
	private ContraindicationQcentityMapper contraindicationQcentityMapper;
	@Resource
	private ContraindicationItemMapper contraindicationItemMapper;
	@Resource
	private SdcCdssItemMapper sdcCdssItemMapper;
	@Resource
	private SdsQcentityMapper sdsQcentityMapper;
	@Resource
	private ContraindicationMapper contraindicationMapper;
	@Autowired
	private IDictionaryService dictionaryService;
	@Autowired
	private CdssApiMapper cdssApiMapper;
	@Autowired
	private ISdcCdssContraindicationMatchService sdcCdssContraindicationMatchService;

	@Override
	public List<ContraindicationEntity> page(Page<ContraindicationEntity> page, Map<String, Object> map) {
		List<ContraindicationEntity> res = this.baseMapper.page(page, map);
		return res;
	}
	@Override
	public List<ContraindicationEntity> list(Map<String, Object> map) {
		return this.baseMapper.list(map);
	}
	@Override
	public List<ContraindicationEntity> getList(Page<ContraindicationEntity> page, Map<String, Object> map) {
		Long entityid = Long.parseLong((String) map.get("entityId"));
		List<Long> contraindicationIdList = contraindicationQcentityMapper.getContraindicationId(entityid);
		List<ContraindicationEntity> res = contraindicationMapper.getListById(page, map);
		List<SdsQcentityEntity> entityList  = sdsQcentityMapper.selectList(null);

		//拼接病种名
//		Map<Long, String> entityMap = entityList.stream().collect(Collectors.toMap(SdsQcentityEntity::getId, SdsQcentityEntity::getBtDesc));
//		for (ContraindicationEntity re : res) {
//			StringBuffer stringBuffer= new StringBuffer("");
//			for (Long  entityId : re.getEntityIdList()) {
//				if (!stringBuffer.toString().equals("")){
//					stringBuffer.append(",");
//				}
//				String s = entityMap.get(entityId);
//				stringBuffer.append(s);
//
//			}
//			re.setEntityName(stringBuffer.toString());
//			System.out.println(re.toString());
//		}
		return res;
	}

	@Override
	public List<ContraindicationEntity> query(Page<ContraindicationEntity> page, Map<String, Object> map) {

		List<ContraindicationEntity> res=contraindicationMapper.queryByName(page,map);
		return res;
	}

	@Override
	public JSONArray getMap() {
		Wrapper<ContraindicationEntity> wrapper = new EntityWrapper<>();
		wrapper.eq("active",1);
		List<ContraindicationEntity> list = this.baseMapper.selectList(wrapper);
		JSONArray res = new JSONArray();
		JSONObject obj = new JSONObject();
		obj.put("value", "");
		obj.put("text","全部");
		res.add(obj);
		for (ContraindicationEntity contraindication : list){
			JSONObject object = new JSONObject();
			object.put("value",contraindication.getId()+"");
			object.put("text",contraindication.getName());
			res.add(object);
		}
		return res;
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(Map<String, Object> params) {
//		List<Long> entityIdList = JSONArray.parseArray(params.get("entityIds").toString(), Long.class);
		ContraindicationEntity contraindication=new ContraindicationEntity();
		contraindication.setName((String) params.get("name"));
		contraindication.setCode((String) params.get("code"));
		contraindication.setInfo((String) params.get("info"));
		contraindication.setActive((Integer) params.get("active"));
		contraindication.setSource((String) params.get("source"));
		contraindicationMapper.insert(contraindication);

//		Long id = contraindication.getId();
//
//		List<ContraindicationQcentity> conQcentityList=new ArrayList<>();
//		for (Long entityId : entityIdList) {
//			ContraindicationQcentity conQcentity=new ContraindicationQcentity();
//			conQcentity.setContraindicationId(id);
//			conQcentity.setEntityId(entityId);
//			conQcentityList.add(conQcentity);
//		}
//
//		conQcentityService.insertBatch(conQcentityList);
	}



	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(Map<String, Object> params) {
//		List<Long> entityIdList = JSONArray.parseArray(params.get("entityIds").toString(), Long.class);

		Long id = Long.parseLong((String) params.get("id"));
		ContraindicationEntity contraindication=new ContraindicationEntity();
		contraindication.setId(id);
		contraindication.setName((String) params.get("name"));
		contraindication.setCode((String) params.get("code"));
		contraindication.setInfo((String) params.get("info"));
		contraindication.setActive((Integer) params.get("active"));
		contraindication.setSource((String) params.get("source"));
		contraindicationMapper.updateAllColumnById(contraindication);

//		Wrapper<ContraindicationQcentity> wrapper=new EntityWrapper<>();
//		wrapper.eq("contraindication_id",id);
//		contraindicationQcentityMapper.delete(wrapper);
//
//		List<ContraindicationQcentity> conQcentityList=new ArrayList<>();
//		for (Long entityId : entityIdList) {
//			ContraindicationQcentity conQcentity=new ContraindicationQcentity();
//			conQcentity.setContraindicationId(id);
//			conQcentity.setEntityId(entityId);
//			conQcentityList.add(conQcentity);
//		}
//		conQcentityService.insertBatch(conQcentityList);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delete(Long contraindicationId) {
		contraindicationMapper.deleteById(contraindicationId);
//		Wrapper<ContraindicationQcentity> wrapper=new EntityWrapper<>();
//		wrapper.eq("contraindication_id",contraindicationId);
//		contraindicationQcentityMapper.delete(wrapper);

		//删除禁忌症相关的诊疗方案禁忌症关联数据,yhw,2024/1/31
		Wrapper<SdcCdssContraindicationMatchEntity> wrapper=new EntityWrapper<>();
		wrapper.eq("contraindication_id",contraindicationId);
		sdcCdssContraindicationMatchService.delete(wrapper);


		Wrapper<ContraindicationItemEntity> itemwrapper=new EntityWrapper<>();
		itemwrapper.eq("contraindication_id",contraindicationId);
		contraindicationItemMapper.delete(itemwrapper);

	}

	@Override
	public List<ContraindicationEntity> getByQcincaseId(Long incaseId) {
		return this.baseMapper.getByQcincaseId(incaseId);
	}




	@Override
	@Transactional(rollbackFor = Exception.class)
	public void importItem(List<List<Object>> contraindicationList) {
		for (int i = 1; i < contraindicationList.size(); i++){
			List<Object> ls = contraindicationList.get(i);

			//病种
			String qcAbbrev = ls.get(0).toString();

			//代码
			String code = ls.get(1).toString();
			//禁忌症名称
			String name = ls.get(2).toString();
			//禁忌症介绍
			String info = ls.get(3).toString();
			//是否有效
			Integer active = CommonUtil.equals(ls.get(4),"是")?1:0;
			// 获取病种信息
			SdsQcentityEntity qcEntity = new SdsQcentityEntity();
			qcEntity.setAbbrev(qcAbbrev);
			qcEntity = this.sdsQcentityMapper.selectOne(qcEntity);
			if (qcEntity==null) {
				continue;
			}
			Long qcentityId = qcEntity.getId();
			//禁忌症
			ContraindicationEntity contraindicationEntity=null;
//			contraindicationEntity.setEntityId(qcentityId);
			contraindicationEntity =  contraindicationMapper.selectOne(contraindicationEntity);

			if (contraindicationEntity == null){
//				contraindicationEntity.setEntityId(qcentityId);

				contraindicationEntity.setCode(code);
				contraindicationEntity.setName(name);
				contraindicationEntity.setInfo(info);
				contraindicationEntity.setActive(active);


				contraindicationMapper.insert(contraindicationEntity);
			}else {
				contraindicationEntity.setCode(code);
				contraindicationEntity.setName(name);
				contraindicationEntity.setInfo(info);
				contraindicationEntity.setActive(active);
				contraindicationMapper.updateAllColumnById(contraindicationEntity);
			}
		}
	}

	@Override
	public JSONArray CIInfo(Long episodeId, Long entityId) {
		JSONArray ciInfo = new JSONArray();
		List<ContraindicationEntity> ciList = this.baseMapper.getListByEntityId(entityId);
		for (ContraindicationEntity ciDic : ciList) {
			JSONObject ciObj = JSONObject.parseObject(JSON.toJSONString(ciDic));
			// 获取审核结果
			SdcBusiContraindicationEntity ciResult = new SdcBusiContraindicationEntity();
			ciResult.setEpisodeId(episodeId);
			ciResult.setContraindicationId(ciDic.getId());
			ciResult = sdcBusiContraindicationMapper.selectOne(ciResult);
			ciObj.put("ciResult", ciResult);
			// 获取触发详细
			Map map = new HashMap();
			map.put("episodeId", episodeId);
			map.put("contraindicationId", ciDic.getId());
			map.put("status", 1);
			List<Map<String, Object>> ciDetail = sdcBusiContraindicationDtlMapper.detail(map);
			ciObj.put("ciDetail", ciDetail);
			ciInfo.add(ciObj);
		}
//		ciInfo = JSONArray.parseArray(JSON.toJSONString(ciList));
		return ciInfo;
	}

	@Override
	public List<Tree<Long>> buildCdssTree(Long entityId) {
		Map<String,Object> map = new HashMap<>();
		List<ZTreeNode> res = new ArrayList<>();
		List<ZTreeNode> parentList =  new ArrayList<>();
		List<ZTreeNode> children1EvalList=  sdcCdssItemMapper.getCdssTreeByEntity(1, entityId);
		List<ZTreeNode> children1TreatList=  sdcCdssItemMapper.getCdssTreeByEntity(4, entityId);
		List<ZTreeNode> children1ExamList=  sdcCdssItemMapper.getCdssTreeByEntity(2, entityId);
		List<ZTreeNode> children1LabList=  sdcCdssItemMapper.getCdssTreeByEntity(3, entityId);
		List<ZTreeNode> children1NurList=  sdcCdssItemMapper.getCdssTreeByEntity(5, entityId);


		List<DictionaryEntity> dictionaryEntities = dictionaryService.queryByTypeCode("SDS", "CDSSRecommendType");
		for (DictionaryEntity dictionaryEntity : dictionaryEntities){
			ZTreeNode parent = new ZTreeNode();
			long id = IdWorker.getId();
			parent.setId(id);
			parent.setpId(0L);
			parent.setName(dictionaryEntity.getDescription());
			parentList.add(parent);
		}

		for (ZTreeNode parent : parentList){
			String name = parent.getName();
			switch (name) {
				case "推荐护理处置":
					for (ZTreeNode zTreeNode1Nur : children1NurList){
						zTreeNode1Nur.setPinyin(name);
						zTreeNode1Nur.setpId(parent.getId());
					}
					break;
				case "推荐检验":
					for (ZTreeNode zTreeNode1Lab : children1LabList){
						zTreeNode1Lab.setPinyin(name);
						zTreeNode1Lab.setpId(parent.getId());
					}
					break;
				case "推荐检查":
					for (ZTreeNode zTreeNode1Exam : children1ExamList){
						zTreeNode1Exam.setPinyin(name);
						zTreeNode1Exam.setpId(parent.getId());
					}
					break;
				case "推荐治疗方案":
					for (ZTreeNode zTreeNode1Treat : children1TreatList){
						zTreeNode1Treat.setPinyin(name);
						zTreeNode1Treat.setpId(parent.getId());
					}
					break;
				case "推荐评估量表":
					for (ZTreeNode zTreeNode1Eval : children1EvalList){
						zTreeNode1Eval.setPinyin(name);
						zTreeNode1Eval.setpId(parent.getId());
					}
					break;
			}
		}


		res.addAll(parentList);
		res.addAll(children1EvalList);
		res.addAll(children1TreatList);
		res.addAll(children1ExamList);
		res.addAll(children1LabList);
		res.addAll(children1NurList);

		TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
		treeNodeConfig.setIdKey("id");
		treeNodeConfig.setParentIdKey("parentId");
		//构建树形
		List<Tree<Long>> trees = TreeUtil.build(res, 0L, treeNodeConfig, ((object, treeNode) -> {
			treeNode.setId(object.getId());//id
			treeNode.setParentId(object.getpId());//父id
			treeNode.putExtra("text", object.getName());
			if (object.getpId()==0) {
				treeNode.putExtra("state", "closed"); //默认全部折叠
			}
		}));
		return trees;
	}

	@Override
	public List<SdsQcentityEntityDto> getEntity() {
		return cdssApiMapper.selectQcentityEntity();
	}

	@Override
	public JSONArray getContraindicationMap() {
		List<ContraindicationEntity> contraindicationEntities = this.baseMapper.selectList(null);
		JSONArray officeArry = new JSONArray();
		JSONObject obj = new JSONObject();
		obj.put("value", "");
		obj.put("text","全部");
		officeArry.add(obj);
		for(ContraindicationEntity contraindicationEntity : contraindicationEntities){
			JSONObject officeObj = new JSONObject();
			officeObj.put("value", contraindicationEntity.getId() + "");
			officeObj.put("text", contraindicationEntity.getName());
			officeArry.add(officeObj);
		}
		return officeArry;
	}

	@Override
	public List<ContraindicationEntity> pageExcludeMatch(Page<ContraindicationEntity> page, Map<String, Object> map, List<Long> excludeIds) {
		return baseMapper.pageExcludeMatch(page,map,excludeIds);
	}


}